package com.example.chen.tabindicatorlib.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.TintTypedArray;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.chen.tabindicatorlib.R;

import org.w3c.dom.Text;

/**
 * Created by chen on 2016/6/29.
 */
public class ViewPageIndicator extends LinearLayout {

    private Paint mPaint;

    private Path mPath;

    private ViewPager mViewPager;

    public static final int SHAPE_TRIANGLE = 1000;
    public static final int SHAPE_LINE = 1001;

    private int currentShapr = SHAPE_LINE;

    public void setmViewPager(ViewPager mViewPager, int position) {
        this.mViewPager = mViewPager;
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                scroll(position, positionOffset);
            }

            @Override
            public void onPageSelected(int position) {
                selectIndexText(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mViewPager.setCurrentItem(position);
        selectIndexText(position);
    }

    private int mTriangleWidth;

    private int mTriangleHeight;

    private String[] mTitles;

    private int ScreenWidth;

    private int selectColor;
    private int UnselectColor;

    public void setmTitles(String[] mTitles) {
        if (mTitles != null && mTitles.length > 0) {
            this.mTitles = mTitles;
            this.removeAllViews();
        }
        initChildView();
    }

    //三角形初始化偏移量
    private int mInitTranslationX;
    //移动tab时按钮的偏移量和根据手指滑动偏移量总和
    private int mTranslationX = 0;

    //三角形宽度占单元格的比例
    private static final float RADIO_TRIANGLE = 1 / 6F;

    private int mChildCount = 0;

    public void setCurrentShapr(int currentShapr) {
        this.currentShapr = currentShapr;
    }

    public ViewPageIndicator(Context context) {
        this(context, null);
    }

    public ViewPageIndicator(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ViewPageIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.setOrientation(HORIZONTAL);
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        ScreenWidth = wm.getDefaultDisplay().getWidth();
        if (attrs != null) {
            final TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs,
                    R.styleable.ViewPageIndicator, defStyleAttr, 0);

            mChildCount = a.getInt(R.styleable.ViewPageIndicator_childCount, 3);

            selectColor = a.getColor(R.styleable.ViewPageIndicator_selectColor, 0xff0000);
            UnselectColor = a.getColor(R.styleable.ViewPageIndicator_UnselectColor, 0x2222ff);
        }
        mPaint = new Paint();
        //抗锯齿
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.parseColor("#ffff0000"));
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setPathEffect(new CornerPathEffect(3));
    }

    private void initChildView() {
        for (int i = 0; i < mTitles.length; i++) {
            TextView tv = new TextView(getContext());
            LinearLayout.LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            layoutParams.width = ScreenWidth / mChildCount;
            tv.setLayoutParams(layoutParams);
            tv.setText(mTitles[i]);
            tv.setTextColor(UnselectColor);
            tv.setPadding(0, 10, 0, 10);
            tv.setGravity(Gravity.CENTER);
            tv.setTag(mTitles[i]);
            addView(tv);
        }
        setItemClickEvent();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View view = getChildAt(i);
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            layoutParams.width = 0;
            layoutParams.width = ScreenWidth / mChildCount;
            view.setLayoutParams(layoutParams);
        }
        setItemClickEvent();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mTriangleWidth = (int) (w / mChildCount * RADIO_TRIANGLE);

        mTriangleHeight = mTriangleWidth / 3;

        mInitTranslationX = w / mChildCount / 2 - mTriangleWidth / 2;
        switch (currentShapr) {
            case SHAPE_LINE:
                initLine();
                break;

            case SHAPE_TRIANGLE:
                initTriangle();
                break;
        }

    }

    private void initTriangle() {
        mPath = new Path();
        mPath.moveTo(0, 0);
        mPath.lineTo(mTriangleWidth, 0);
        mPath.lineTo(mTriangleWidth / 2, -mTriangleHeight);
        mPath.close();
    }

    private void initLine() {
        mPath = new Path();
        mPath.moveTo(0, 0);
        mPath.lineTo(mTriangleWidth, 0);
        mPath.lineTo(mTriangleWidth, -5);
        mPath.lineTo(0, -5);
        mPath.close();
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {

        canvas.save();
        //移动画布，将画布移动到单元格正下方
        canvas.translate(mInitTranslationX + mTranslationX, getHeight());

        canvas.drawPath(mPath, mPaint);

        canvas.restore();

        super.dispatchDraw(canvas);
    }

    public void setmChildCount(int mChildCount) {
        this.mChildCount = mChildCount;
    }

    public void scroll(int position, float positionOffset) {
        int tabWidth = getWidth() / mChildCount;
        mTranslationX = (int) ((position + positionOffset) * tabWidth);

        if (position > mChildCount - 2 && getChildCount() > mChildCount && positionOffset > 0) {
            if (mChildCount != 1) {
                this.scrollTo(((position - mChildCount + 2) * tabWidth + (int) positionOffset * tabWidth), 0);
            } else {
                this.scrollTo((tabWidth * position + (int) (tabWidth * positionOffset)), 0);
            }
        }


        invalidate();
    }


    private void resetAllTextColor() {
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            if (view instanceof TextView) {
                ((TextView) view).setTextColor(UnselectColor);
            }
        }
    }

    private void selectIndexText(int pos) {
        resetAllTextColor();
        View view = getChildAt(pos);
        if (view instanceof TextView) {
            ((TextView) view).setTextColor(selectColor);
        }
    }


    private void setItemClickEvent() {
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            final int position = i;
            View view = getChildAt(i);
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    mViewPager.setCurrentItem(position);
                    //selectIndexText(position);
                }
            });
        }
    }
}
